//
//  UtilCheck.m
//  ydcb
//
//  Created by heyue on 13-5-6.
//  Copyright 2013年 Apple inc. All rights reserved.
//

#import "UtilCheck.h"
#include <sys/socket.h> // Per msqr
#include <sys/sysctl.h>
#include <net/if.h>
#include <net/if_dl.h>

#import "RcMD5.h"
#import "TQLocationConverter.h"

#define KEEP @"KEEP"
#define START @"START"
#define SHARE @"SHARE"
#define APPExamine @"examine"//APP审核
#define LANGUAGE @"LANGUAGE"//APP审核

#define HEADIMAGETIME @"touxiangguoqishijian" //头像过期时间
#import "BaseModel.h"



@implementation UtilCheck

//16进制颜色(html颜色值)字符串转为UIColor
+(UIColor *) hexStringToColor: (NSString *) stringToConvert  alpha:(CGFloat)alpha{
    NSString *cString = [[stringToConvert stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] uppercaseString];
    // String should be 6 or 8 characters
    if ([cString length] < 6)
        return [UIColor blackColor];
    // strip 0X if it appears
    if ([cString hasPrefix:@"0X"])
        cString = [cString substringFromIndex:2];
    if ([cString hasPrefix:@"#"])
        cString = [cString substringFromIndex:1];
    if ([cString length] != 6)
        return [UIColor blackColor];
    // Separate into r, g, b substrings
    NSRange range;
    range.location = 0;
    range.length = 2;
    NSString *rString = [cString substringWithRange:range];
    range.location = 2;
    NSString *gString = [cString substringWithRange:range];
    range.location = 4;
    NSString *bString = [cString substringWithRange:range];
    // Scan values
    unsigned int r, g, b;
    [[NSScanner scannerWithString:rString] scanHexInt:&r];
    [[NSScanner scannerWithString:gString] scanHexInt:&g];
    [[NSScanner scannerWithString:bString] scanHexInt:&b];
    if(alpha==0){
        alpha=0.01;
    }
    return [UIColor colorWithRed:((float) r / 255.0f) green:((float) g / 255.0f) blue:((float) b / 255.0f)                         alpha:alpha];
    
}



//获得设备型号
+ (NSString *)getCurrentDeviceModel
{
    int mib[2];
    size_t len;
    char *machine;
    
    mib[0] = CTL_HW;
    mib[1] = HW_MACHINE;
    sysctl(mib, 2, NULL, &len, NULL, 0);
    machine = malloc(len);
    sysctl(mib, 2, machine, &len, NULL, 0);
    
    NSString *platform = [NSString stringWithCString:machine encoding:NSASCIIStringEncoding];
    free(machine);
    // iPhone
    if ([platform isEqualToString:@"iPhone1,1"]) return @"iPhone2G";
    if ([platform isEqualToString:@"iPhone1,2"]) return @"iPhone3G";
    if ([platform isEqualToString:@"iPhone2,1"]) return @"iPhone3GS";
    if ([platform isEqualToString:@"iPhone3,1"]) return @"iPhone4";
    if ([platform isEqualToString:@"iPhone3,2"]) return @"iPhone4";
    if ([platform isEqualToString:@"iPhone3,3"]) return @"iPhone4";
    if ([platform isEqualToString:@"iPhone4,1"]) return @"iPhone4S";
    if ([platform isEqualToString:@"iPhone5,1"]) return @"iPhone5";
    if ([platform isEqualToString:@"iPhone5,2"]) return @"iPhone5";
    if ([platform isEqualToString:@"iPhone5,3"]) return @"iPhone5c";
    if ([platform isEqualToString:@"iPhone5,4"]) return @"iPhone5c";
    if ([platform isEqualToString:@"iPhone6,1"]) return @"iPhone5s";
    if ([platform isEqualToString:@"iPhone6,2"]) return @"iPhone5s";
    if ([platform isEqualToString:@"iPhone7,2"]) return @"iPhone6";
    if ([platform isEqualToString:@"iPhone7,1"]) return @"iPhone6Plus";
    if ([platform isEqualToString:@"iPhone8,1"]) return @"iPhone6s";
    if ([platform isEqualToString:@"iPhone8,2"]) return @"iPhone6sPlus";
    if ([platform isEqualToString:@"iPhone8,3"]) return @"iPhoneSE";
    if ([platform isEqualToString:@"iPhone8,4"]) return @"iPhoneSE";
    if ([platform isEqualToString:@"iPhone9,1"]) return @"iPhone7";
    if ([platform isEqualToString:@"iPhone9,2"]) return @"iPhone7Plus";
    if ([platform isEqualToString:@"iPhone10,1"]) return @"iPhone8";
    if ([platform isEqualToString:@"iPhone10,4"]) return @"iPhone8";
    if ([platform isEqualToString:@"iPhone10,2"]) return @"iPhone8Plus";
    if ([platform isEqualToString:@"iPhone10,5"]) return @"iPhone8Plus";
    if ([platform isEqualToString:@"iPhone10,3"]) return @"iPhoneX";
    if ([platform isEqualToString:@"iPhone10,6"]) return @"iPhoneX";
    
    //iPod Touch
    if ([platform isEqualToString:@"iPod1,1"])   return @"iPodTouch";
    if ([platform isEqualToString:@"iPod2,1"])   return @"iPodTouch2G";
    if ([platform isEqualToString:@"iPod3,1"])   return @"iPodTouch3G";
    if ([platform isEqualToString:@"iPod4,1"])   return @"iPodTouch4G";
    if ([platform isEqualToString:@"iPod5,1"])   return @"iPodTouch5G";
    if ([platform isEqualToString:@"iPod7,1"])   return @"iPodTouch6G";
    
    //iPad
    if ([platform isEqualToString:@"iPad1,1"])   return @"iPad";
    if ([platform isEqualToString:@"iPad2,1"])   return @"iPad2";
    if ([platform isEqualToString:@"iPad2,2"])   return @"iPad2";
    if ([platform isEqualToString:@"iPad2,3"])   return @"iPad2";
    if ([platform isEqualToString:@"iPad2,4"])   return @"iPad2";
    if ([platform isEqualToString:@"iPad3,1"])   return @"iPad3";
    if ([platform isEqualToString:@"iPad3,2"])   return @"iPad3";
    if ([platform isEqualToString:@"iPad3,3"])   return @"iPad3";
    if ([platform isEqualToString:@"iPad3,4"])   return @"iPad4";
    if ([platform isEqualToString:@"iPad3,5"])   return @"iPad4";
    if ([platform isEqualToString:@"iPad3,6"])   return @"iPad4";
    
    //iPad Air
    if ([platform isEqualToString:@"iPad4,1"])   return @"iPadAir";
    if ([platform isEqualToString:@"iPad4,2"])   return @"iPadAir";
    if ([platform isEqualToString:@"iPad4,3"])   return @"iPadAir";
    if ([platform isEqualToString:@"iPad5,3"])   return @"iPadAir2";
    if ([platform isEqualToString:@"iPad5,4"])   return @"iPadAir2";
    
    //iPad mini
    if ([platform isEqualToString:@"iPad2,5"])   return @"iPadmini1G";
    if ([platform isEqualToString:@"iPad2,6"])   return @"iPadmini1G";
    if ([platform isEqualToString:@"iPad2,7"])   return @"iPadmini1G";
    if ([platform isEqualToString:@"iPad4,4"])   return @"iPadmini2";
    if ([platform isEqualToString:@"iPad4,5"])   return @"iPadmini2";
    if ([platform isEqualToString:@"iPad4,6"])   return @"iPadmini2";
    if ([platform isEqualToString:@"iPad4,7"])   return @"iPadmini3";
    if ([platform isEqualToString:@"iPad4,8"])   return @"iPadmini3";
    if ([platform isEqualToString:@"iPad4,9"])   return @"iPadmini3";
    if ([platform isEqualToString:@"iPad5,1"])   return @"iPadmini4";
    if ([platform isEqualToString:@"iPad5,2"])   return @"iPadmini4";
    
    if ([platform isEqualToString:@"i386"])      return @"iPhoneSimulator";
    if ([platform isEqualToString:@"x86_64"])    return @"iPhoneSimulator";
    return platform;
}

/**
 * 色值
 */
+(UIColor*)getRZColor:(CGFloat)red green:(CGFloat)green blue:(CGFloat)blue alpha:(CGFloat)alpha{
    //    if(alpha==0){
    //        return [UIColor colorWithHue:<#(CGFloat)#> saturation:<#(CGFloat)#> brightness:<#(CGFloat)#> alpha:<#(CGFloat)#>];
    //    }
    return [UIColor colorWithRed:red/255.0f green:green/255.0f blue:blue/255.0f alpha:alpha] ;
}
/**
 * 比较浮点大小
 @param type 返回类型 0 大值 1 小值
 */
+(CGFloat)Returnsize:(CGFloat)float1  size1:(CGFloat)float2 type:(NSInteger)type{
    if(float1==float2){
        return float1;
    }
    else if(float1>float2){
        if(0==type){
            return float1;
        }
        else{
            return float2;
        }
    }
    else{
        if(0==type){
            return float2;
        }
        else{
            return float1;
        }
    }
}


/**
 *字符串匹配截取
 */
//@param sourceString 源字符串
//@param NSRange 需要匹配的目标字符串
//@param Type   截取类型 0 前 1后
+(NSString*)substring:(NSString*)sourceString NSRange:(NSString*)RangeString Type:(NSInteger)RangeType{
    
    NSRange range = [sourceString rangeOfString:RangeString];//匹配得到的下标
    
    if(0==RangeType){
        if(range.length>0){
            sourceString = [sourceString substringToIndex:range.location];//截取范围类的字符串
        }
        
    }
    else{
        sourceString = [sourceString substringFromIndex:(range.location+range.length)];//截取范围类的字符串
    }
    
    
    return sourceString;
}

/**
 *字符串截取
 */
//@param sourceString 源字符串
//@param Type   截取类型 0 前 1后
//@param SubLength   截取长度
+(NSString*)substring:(NSString*)sourceString Type:(NSInteger)RangeType SubLength:(NSInteger)len{
    
    
    if(0==RangeType){
        
        sourceString = [sourceString substringToIndex:len];//截取范围类的字符串
    }
    else{
        
        sourceString = [sourceString substringFromIndex:(sourceString.length-len)];//截取范围类的字符串
    }
    return sourceString;
}
/**
 *字符串替换
 */
//@param sourceString 源字符串
//@param Replace 需要替换的源字符串
//@param Target  替换成的字符串
+ (NSString*)stringreplace:(NSString*)sourceString Replace:(NSString*)replaceString Target:(NSString*)targetString {
    
    if([sourceString rangeOfString:replaceString].location !=NSNotFound){
        return [sourceString stringByReplacingOccurrencesOfString:replaceString withString:targetString];
    }
    return sourceString;
}

/**
 *文件是否纯在
 @param filePath 文件路劲
 */
+(BOOL)Ishavefile:(NSString*)filePath{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    if(![fileManager fileExistsAtPath:filePath]) //如果不存在
        
    {
        return NO;
        
    }
    else{
        return YES;
    }
}

/**
 *统一按钮题颜色 type 未方案
 */
+(UIColor*)CustomButtonBackgroundColor:(NSInteger)type{
    if (!type){
        type=0;
    }
    switch (type) {
        case 0:
        {
            return [self getRZColor:0 green:0 blue:0 alpha:1];
        }
            break;
        case 1:
        {
            return [self getRZColor:255 green:255 blue:255 alpha:1];
        }
            break;
        default:
        {
            return [self getRZColor:0 green:0 blue:0 alpha:1];
        }
            break;
    }
    
}

/**
 *统一线条题颜色 type 未方案
 */
+(UIColor*)CustomseparatorColor:(NSInteger)type{
    if (!type){
        type=0;
    }
    switch (type) {
        case 0:
        {
            return [self getRZColor:0 green:0 blue:0 alpha:1];
        }
            break;
        case 1:
        {
            return [self getRZColor:255 green:255 blue:255 alpha:1];
        }
            break;
        default:
        {
            return [self getRZColor:0 green:0 blue:0 alpha:1];
        }
            break;
    }
}
/**
 *统一主标题颜色 type 未方案
 */
+(UIColor*)TitleColor:(NSInteger)type{
    if (!type){
        type=0;
    }
    switch (type) {
        case 0:
        {
            return [self getRZColor:0 green:0 blue:0 alpha:1];
        }
            break;
        case 1:
        {
            return [self getRZColor:255 green:255 blue:255 alpha:1];
        }
            break;
        default:
        {
            return [self getRZColor:0 green:0 blue:0 alpha:1];
        }
            break;
    }
    
}
/**
 *统一副标题颜色 type 为方案
 */
+(UIColor*)SubtitleColor:(NSInteger)type{
    if (!type){
        type=0;
    }
    switch (type) {
        case 0:
        {
            return [self getRZColor:0 green:0 blue:0 alpha:1];
        }
            break;
        case 1:
        {
            return [self getRZColor:255 green:255 blue:255 alpha:1];
        }
            break;
        default:
        {
            return [self getRZColor:0 green:0 blue:0 alpha:1];
        }
            break;
    }
    
}

/**
 *统一导航颜色
 */
+(UIImage*)NavigationControllerImageByColor:(UIColor*)navcolor {
    return [UtilCheck ClearBlackNavigation:navcolor ];
}

/**
 *统一导航颜色
 */
+(UIColor*)NavigationControllerColor{
    return  NAVCOLOR;
}

/**
 *统一视图背景颜色
 */
+(UIColor*)Backgroundcolor{
    return [self hexStringToColor:myBackColor  alpha:1];
}
/**
 *时间戳转标准时间 指定格式时间字符串
 */
+(NSString*)TimestampToDate:(NSString*)timestamp Formatter:(NSString*)fortter{
    
    if(!([timestamp hasPrefix:@"("]&&[timestamp hasSuffix:@")"])){
        return @"NULL";
    }
    int start = 0;//“（”的位置
    int end = 0;//“）”的位置
    for (int i = 0; i < timestamp.length; i++) {
        if ([timestamp characterAtIndex:i] == '(') {
            start = i;
        }
        if ([timestamp characterAtIndex:i] == ')') {
            end = i;
        }
    }
    
    NSString *publishString = [timestamp substringToIndex:end];
    publishString = [publishString substringFromIndex:start + 1];
    
    double publishLong = [publishString doubleValue];
    
    
    
    NSDate *publishDate = [NSDate dateWithTimeIntervalSince1970:publishLong];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [formatter setDateFormat:fortter];
    
    //解析后台时间戳需要加上这些代码 因为后台那边日期少了8小时
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    publishDate = [publishDate  dateByAddingTimeInterval: interval];
    //end
    
    publishString = [formatter stringFromDate:publishDate];
    
    return publishString;
}


+ (NSString*)hexStringForData:(NSData*)data

{
    
    if (data == nil) {
        
        return nil;
        
    }
    
    
    NSMutableString* hexString = [NSMutableString string];
    
    
    const unsigned char *p = [data bytes];
    
    
    
    for (int i=0; i < [data length]; i++) {
        
        [hexString appendFormat:@"%02x", *p++];
        
    }
    
    return hexString;
    
}




/**
 *日期字符串 标准时间指定格式
 */
+(NSDate*)dateByString:(NSString*)string  oldFormatter:(NSString*)oldformatter dateFormatter:(NSString*)formatter{
    
    NSDateFormatter *format=[[NSDateFormatter alloc] init] ;
    [format setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];
    
    
    [format setDateFormat:oldformatter];
    string=[self stringByDate:[format dateFromString:string] dateFormatter:formatter];
    
    [format setDateFormat:formatter];
    return [format dateFromString:string];
    
}

/**
 *标准时间指定格式时间转
 */
+(NSString*)stringByDate:(NSDate*)date  dateFormatter:(NSString*)formatter{
    
    
    NSDateFormatter *format=[[NSDateFormatter alloc] init] ;
    [format setTimeZone:[NSTimeZone timeZoneWithName:@"Asia/Shanghai"]];
    [format setDateFormat:formatter];
    return [format stringFromDate:date];
    
}

/**
 *标准时间指定格式时间转时间戳
 */
+(NSString*)DateToTimestamp{
    
    NSDate *datenow = [NSDate date];//现在时间,你可以输出来看下是什么格式
    
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    
    NSInteger interval = [zone secondsFromGMTForDate:datenow];
    
    NSDate *localeDate = [datenow  dateByAddingTimeInterval:interval];
    
    NSString *timeSp = [NSString stringWithFormat:@"%ld",(long)[localeDate timeIntervalSince1970]];
    
    return timeSp;
}

/**
 *标准化json
 */
+(NSDictionary*)FormatJSON:(NSDictionary*)responseObject{
    
    NSString *json=[UtilCheck dictionaryToJson:[NSMutableDictionary dictionaryWithDictionary:responseObject]];
    
    json=[json stringByReplacingOccurrencesOfString:@"%" withString:@"%%"];
    json=[json stringByReplacingOccurrencesOfString:@"'" withString:@"‘"];
    json=[json stringByReplacingOccurrencesOfString:@"?" withString:@" "];
    json=[json stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    
    json=[json stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"\v" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"\f" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"\b" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"\a" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"\e" withString:@""];
    json=[json stringByReplacingOccurrencesOfString:@"':," withString:@"':'',"];
    json=[json stringByReplacingOccurrencesOfString:@"':}" withString:@"':''}"];
    json=[json stringByReplacingOccurrencesOfString:@"'" withString:@"\""];
    json =[json stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
    json =[json stringByReplacingOccurrencesOfString:@"<null>" withString:@""];
    json =[json stringByReplacingOccurrencesOfString:@"null" withString:@"\"\""];
    
    return [UtilCheck  dictionaryWithJsonString:json];
}

+ (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    jsonString = [self removeUnescapedCharacter:jsonString];
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err=nil;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        return nil;
    }
    return dic;
}

+ (NSString *)removeUnescapedCharacter:(NSString *)inputStr{    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    
    //获取那些特殊字符
    NSRange range = [inputStr rangeOfCharacterFromSet:controlChars];
    //寻找字符串中有没有这些特殊字符
    if (range.location != NSNotFound)    {
        NSMutableString *mutable = [NSMutableString stringWithString:inputStr];
        while (range.location != NSNotFound)
        {
            [mutable deleteCharactersInRange:range];
            //去掉这些特殊字符
            range = [mutable rangeOfCharacterFromSet:controlChars];        }
        return mutable;
    }
    return inputStr;
}



/**
 *当前时间和本地缓存时间差秒
 */
+(CGFloat)TimeCache:(NSString*)Cachedate{
    
    NSDateFormatter * formatter = [[NSDateFormatter  alloc ]  init ];
    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSTimeInterval  timeInterval = [[formatter dateFromString:Cachedate] timeIntervalSinceNow];
    return  fabs (timeInterval);
}

/**
 *当前时间和时间戳的时间差
 */
+(NSDateComponents*)Timestamp:(NSString*)Cachedate{
    
    NSDate *NewDate=[NSDate date];
    
    NSDateFormatter * formatter = [[NSDateFormatter  alloc ]  init ];
    [formatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]];
    
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    NSString *olddate=[UtilCheck TimestampToDate:[NSString stringWithFormat:@"(%@)",Cachedate] Formatter:@"yyyy-MM-dd HH:mm:ss"];
    NSDate *OldDate=[formatter dateFromString:olddate];
    NSCalendar *calendars = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    NSDateComponents *comps = [[NSDateComponents alloc] init];
    NSInteger unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit |
    NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit;
    comps=[calendars components:unitFlags fromDate:OldDate toDate:NewDate options:0];
    
    return comps;
}

/**
 *当前时间和时间戳的时间差
 */
+(NSString *)intervalSinceNow: (NSString *) theDate

{
    if(!([theDate hasPrefix:@"("]&&[theDate hasSuffix:@")"])){
        return @"NULL";
    }
    
    
    int start = 0;//“（”的位置
    int end = 0;//“）”的位置
    for (int i = 0; i < theDate.length; i++) {
        if ([theDate characterAtIndex:i] == '(') {
            start = i;
        }
        if ([theDate characterAtIndex:i] == ')') {
            end = i;
        }
    }
    
    NSString *publishString = [theDate substringToIndex:end];
    publishString = [publishString substringFromIndex:start + 1];
    
    double publishLong = [publishString doubleValue];
    
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:publishLong];
    
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateStyle:NSDateFormatterMediumStyle];
    [formatter setTimeStyle:NSDateFormatterShortStyle];
    [formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"UTC"]];
    [formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    //解析后台时间戳需要加上这些代码 因为后台那边日期少了8小时
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate:date];
    d = [d  dateByAddingTimeInterval: interval];
    //end
    
    NSTimeInterval late=[d timeIntervalSince1970]*1;
    
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    
    NSString *timeString=@"";
    
    
    
    NSTimeInterval cha=(now-late);
    
    if(cha<1){
        //        return[THMangerTool language:@"time.just"];
    }
    
    else if (cha/3600<1) {
        
        
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        
        timeString = [timeString substringToIndex:timeString.length-7];
        
        //        timeString=[NSString stringWithFormat:@"%@%@%@", timeString,[THMangerTool language:@"time.minute"],[THMangerTool language:@"time.before"]];
        
        
        
    }
    
    else if (cha/3600>1&&cha/86400<1) {
        
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        timeString = [timeString substringToIndex:timeString.length-7];
        //        timeString=[NSString stringWithFormat:@"%@%@%@", timeString,[THMangerTool language:@"time.hour"],[THMangerTool language:@"time.before"]];
    }
    
    else if (cha/86400>1&&cha/86400<7)
        
    {
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        timeString = [timeString substringToIndex:timeString.length-7];
        //        timeString=[NSString stringWithFormat:@"%@%@%@", timeString,[THMangerTool language:@"time.day"],[THMangerTool language:@"time.before"]];
        
    }
    else{
        //        timeString=[NSString stringWithFormat:@"%@%@%@", @"7",[THMangerTool language:@"time.day"],[THMangerTool language:@"time.before"]];
    }
    return timeString;
    
    
}

/**
 *倒计时
 */
+(NSString *)countdown: (NSString *) theDate
{
    
    
    NSTimeInterval late=[[UtilCheck dateByString:theDate oldFormatter:@"yyyy-MM-dd HH:mm" dateFormatter:@"yyyy-MM-dd HH:mm"] timeIntervalSince1970]*1;//[d timeIntervalSince1970]*1;
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    
    NSTimeInterval now=[dat timeIntervalSince1970]*1;
    
    NSString *timeString=@"";
    
    
    
    NSTimeInterval cha=(late-now);
    
    if(cha<1){
        //时间超出
        return nil;
    }
    
    else if (cha/3600<1) {
        
        
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        
        timeString = [timeString substringToIndex:timeString.length-7];
        
        //        timeString=[NSString stringWithFormat:@"%@%@", timeString,[THMangerTool language:@"time.minute"]];
        //活动即将开启
        timeString=@"0";
        
    }
    
    else if (cha/3600>1&&cha/86400<1) {
        
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        
        timeString = [timeString substringToIndex:timeString.length-7];
        
        //        timeString=[NSString stringWithFormat:@"%@%@", timeString,[THMangerTool language:@"time.hour"]];
        
        //活动即将开启
        if([timeString intValue]==1){
            timeString=@"0";
            
        }
        
        
    }
    
    else
    {
        
        timeString = [NSString stringWithFormat:@"%f", cha/86400];
        
        timeString = [timeString substringToIndex:timeString.length-7];
        
        //        timeString=[NSString stringWithFormat:@"%@%@", timeString,[THMangerTool language:@"time.minute"]];
        
        NSString *  HH  = [NSString stringWithFormat:@"%f", ((cha-[timeString intValue]*86400)/3600)];
        
        HH = [HH substringToIndex:HH.length-7];
        
        if([HH intValue]>0){
            //            HH=[NSString stringWithFormat:@"%@%@", HH,[THMangerTool language:@"time.hour"]];
            timeString= [timeString stringByAppendingString:HH];
        }
        
        
    }
    
    
    
    
    
    return timeString;
    
    
}

/**
 *判断是否有特殊字符
 */
+(BOOL)IsSpecialString:(NSString *)str{
    NSString *regex = @"[a-zA-Z\u4e00-\u9fa5][a-zA-Z0-9\u4e00-\u9fa5]+";
    NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    
    if(![pred evaluateWithObject:str]){
        return YES;
    }
    return NO;
}
/**
 *清理html代码
 */
+(NSString *)flattenHTML:(NSString *)html trimWhiteSpace:(BOOL)trim {
    NSScanner *theScanner = [NSScanner scannerWithString:html];
    NSString *text = nil;
    
    while ([theScanner isAtEnd] == NO) {
        // find start of tag
        [theScanner scanUpToString:@"<" intoString:NULL] ;
        // find end of tag
        [theScanner scanUpToString:@">" intoString:&text] ;
        // replace the found tag with a space
        //(you can filter multi-spaces out later if you wish)
        html = [html stringByReplacingOccurrencesOfString:
                [ NSString stringWithFormat:@"%@>", text]
                                               withString:@""];
    }
    
    html = [html stringByReplacingOccurrencesOfString:@"\r"
                                           withString:@""];
    html = [html stringByReplacingOccurrencesOfString:@"\n"
                                           withString:@""];
    
    // trim off whitespace
    return trim ? [html stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] : html;
}
/**
 *字典转json
 */
+(NSString*)dictionaryToJson:(NSMutableDictionary *)dic;
{
    NSError *parseError = nil;
    NSData  *jsonData = [NSJSONSerialization dataWithJSONObject:dic options:NSJSONWritingPrettyPrinted error:&parseError];
    
    return  [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
}

//判断是否有值
+(BOOL)DataIsNuLL:(NSString *)string{
    if(string.length>0){
        return NO;
    }
    return YES;
}

//判断是否都是数字
+(BOOL)IsAllNum:(NSString *)string{
    unichar c;
    for (int i=0; i<string.length; i++) {
        c=[string characterAtIndex:i];
        if (!isdigit(c)) {
            return NO;
        }
    }
    return YES;
}
//判断是否式合法email
+(BOOL) IsvalidateEmail: (NSString *) candidate
{
    NSString *emailRegex = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:candidate];
}

/*手机号码验证 MODIFIED BY HELENSONG*/
+(BOOL) isValidateMobile:(NSString *)mobileNum
{
    mobileNum=[self stringreplace:mobileNum Replace:@"-" Target:@""];
    //    //手机号以13， 15，18开头，八个 \d 数字字符
    //    NSString *phoneRegex = @"^((1[3-9][0-9])|(1[3-9][^4,\\D])|(1[3-9][0,0-9]))\\d{8}$";
    //    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    //    //    NSLog(@"phoneTest is %@",phoneTest);
    //    return [phoneTest evaluateWithObject:mobileNum];
    
    
    /**
     
     * 手机号码
     
     * 移动：134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     
     * 联通：130,131,132,152,155,156,185,186
     
     * 电信：133,1349,153,180,189
     
     */
    
    NSString * MOBILE = @"^1([0-9][0-9])\\d{8}$";//|5[0-35-9]|8[025-9]
    
    /**
     
     10         * 中国移动：China Mobile
     
     11         * 134[0-8],135,136,137,138,139,150,151,157,158,159,182,187,188
     
     12         */
    
    NSString * CM = @"^1([0-9][0-9])\\d{8}$";// @"^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d{7}$";
    
    /**
     
     15         * 中国联通：China Unicom
     
     16         * 130,131,132,152,155,156,185,186
     
     17         */
    
    NSString * CU =  @"^1([0-9][0-9])\\d{8}$";//@"^1(3[0-2]|5[256]|8[56])\\d{8}$";
    
    /**
     
     20         * 中国电信：China Telecom
     
     21         * 133,1349,153,180,189
     
     22         */
    
    NSString * CT = @"^1([0-9][0-9])\\d{8}$";// @"^1((33|53|8[09])[0-9]|349)\\d{7}$";
    
    /**
     
     25         * 大陆地区固话及小灵通
     
     26         * 区号：010,020,021,022,023,024,025,027,028,029
     
     27         * 号码：七位或八位
     
     28         */
    
    NSString * PHS = @"^0(10|[0-9][0-5789]|\\d{3})\\d{7,8}$";
    
    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", MOBILE];
    
    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CM];
    
    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CU];
    
    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", CT];
    
    NSPredicate *regextestphs = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", PHS];
    
    
    if(([regextestmobile evaluateWithObject:mobileNum] == YES)
       
       || ([regextestcm evaluateWithObject:mobileNum] == YES)
       
       || ([regextestct evaluateWithObject:mobileNum] == YES)
       
       || ([regextestcu evaluateWithObject:mobileNum] == YES)  || ([regextestphs evaluateWithObject:mobileNum] == YES))
        
    {
        
        return YES;
        
    }
    
    else
        
    {
        
        return NO;
        
    }
    
}

/**
 *密码验证
 */
+(BOOL) isValidatePassword:(NSString *)password{
    if(password.length<6){
        return NO;
    }
    else{
        if([self IsExistsChinese:password]){
            return NO;
        }
        else{
            return YES;
        }
        
    }
    
    
}
//判断是否是中文字符
+(BOOL) IsExistsChinese:(NSString *)CheckStr
{
    int length = (int)[CheckStr length];
    // int temp=0;
    for(int i = 0; i < length ; i++)
    {
        NSRange range = NSMakeRange(i,1);
        NSString *subString = [CheckStr substringWithRange:range];
        const char *CString =[subString UTF8String];
        if(strlen(CString) == 3)
            return   YES;   //有中文
        // temp = [CheckStr characterAtIndex:i];
        //if(temp > 0x4e00 && temp < 0x9ff)
        //  return YES;
    }
    return NO;
}
/**
 *去掉空格 isends 是否仅去掉首位两端 default NO
 */
+ (NSString*)clearSpace:(NSString *)str isends:(BOOL)is{
    if(is){
        return  [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    }
    else
    {
        return   [str stringByReplacingOccurrencesOfString:@" " withString:@""];
    }
}

//农历转换函数
+(NSString *)LunarForSolar:(NSDate *)solarDate{
    //天干名称
    //  NSArray *cTianGan = [NSArray arrayWithObjects:@"甲",@"乙",@"丙",@"丁",@"戊",@"己",@"庚",@"辛",@"壬",@"癸", nil];
    
    //地支名称
    //  NSArray *cDiZhi = [NSArray arrayWithObjects:@"子",@"丑",@"寅",@"卯",@"辰",@"巳",@"午",@"未",@"申",@"酉",@"戌",@"亥",nil];
    
    //属相名称
    //  NSArray *cShuXiang = [NSArray arrayWithObjects:@"鼠",@"牛",@"虎",@"兔",@"龙",@"蛇",@"马",@"羊",@"猴",@"鸡",@"狗",@"猪",nil];
    
    //农历日期名
    NSArray *cDayName = [NSArray arrayWithObjects:@"*",@"初一",@"初二",@"初三",@"初四",@"初五",@"初六",@"初七",@"初八",@"初九",@"初十",
                         @"十一",@"十二",@"十三",@"十四",@"十五",@"十六",@"十七",@"十八",@"十九",@"二十",
                         @"廿一",@"廿二",@"廿三",@"廿四",@"廿五",@"廿六",@"廿七",@"廿八",@"廿九",@"三十",nil];
    
    //农历月份名
    NSArray *cMonName = [NSArray arrayWithObjects:@"*",@"正",@"二",@"三",@"四",@"五",@"六",@"七",@"八",@"九",@"十",@"十一",@"腊",nil];
    
    //公历每月前面的天数
    const int wMonthAdd[12] = {0,31,59,90,120,151,181,212,243,273,304,334};
    
    //农历数据
    const int wNongliData[100] = {2635,333387,1701,1748,267701,694,2391,133423,1175,396438
        ,3402,3749,331177,1453,694,201326,2350,465197,3221,3402
        ,400202,2901,1386,267611,605,2349,137515,2709,464533,1738
        ,2901,330421,1242,2651,199255,1323,529706,3733,1706,398762
        ,2741,1206,267438,2647,1318,204070,3477,461653,1386,2413
        ,330077,1197,2637,268877,3365,531109,2900,2922,398042,2395
        ,1179,267415,2635,661067,1701,1748,398772,2742,2391,330031
        ,1175,1611,200010,3749,527717,1452,2742,332397,2350,3222
        ,268949,3402,3493,133973,1386,464219,605,2349,334123,2709
        ,2890,267946,2773,592565,1210,2651,395863,1323,2707,265877};
    
    static int wCurYear,wCurMonth,wCurDay;
    static int nTheDate,nIsEnd,m,k,n,i,nBit;
    
    //取当前公历年、月、日
    NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:solarDate];
    wCurYear =  (int)[components year];
    wCurMonth = (int)[components month];
    wCurDay = (int)[components day];
    
    NSLog(@"year=%d,month=%d,day=%d",wCurYear,wCurMonth,wCurDay);
    
    //计算到初始时间1921年2月8日的天数：1921-2-8(正月初一)
    nTheDate = (wCurYear - 1921) * 365 + (wCurYear - 1921) / 4 + wCurDay + wMonthAdd[wCurMonth - 1] - 38;
    if((!(wCurYear % 4)) && (wCurMonth > 2))
        nTheDate = nTheDate + 1;
    
    //计算农历天干、地支、月、日
    nIsEnd = 0;
    m = 0;
    while(nIsEnd != 1)
    {
        if(wNongliData[m] < 4095)
            k = 11;
        else
            k = 12;
        n = k;
        while(n>=0)
        {
            //获取wNongliData(m)的第n个二进制位的值
            nBit = wNongliData[m];
            for(i=1;i<n+1;i++)
                nBit = nBit/2;
            
            nBit = nBit % 2;
            
            if (nTheDate <= (29 + nBit))
            {
                nIsEnd = 1;
                break;
            }
            
            nTheDate = nTheDate - 29 - nBit;
            n = n - 1;
        }
        if(nIsEnd)
            break;
        m = m + 1;
    }
    wCurYear = 1921 + m;
    wCurMonth = k - n + 1;
    wCurDay = nTheDate;
    if (k == 12)
    {
        if (wCurMonth == wNongliData[m] / 65536 + 1)
            wCurMonth = 1 - wCurMonth;
        else if (wCurMonth > wNongliData[m] / 65536 + 1)
            wCurMonth = wCurMonth - 1;
    }
    
    //生成农历天干、地支、属相
    // NSString *szShuXiang = (NSString *)[cShuXiang objectAtIndex:((wCurYear - 4) % 60) % 12];
    // NSString *szNongli = [NSString stringWithFormat:@"%@(%@%@)年",szShuXiang, (NSString *)[cTianGan objectAtIndex:((wCurYear - 4) % 60) % 10],(NSString *)[cDiZhi objectAtIndex:((wCurYear - 4) % 60) % 12]];
    
    //生成农历月、日
    NSString *szNongliDay;
    if (wCurMonth < 1){
        //        szNongliDay = [NSString stringWithFormat:@"%@%@",[THMangerTool language:@"time.run"],(NSString *)[cMonName objectAtIndex:-1 * wCurMonth]];
    }
    else{
        szNongliDay = (NSString *)[cMonName objectAtIndex:wCurMonth];
    }
    
    //  NSString *lunarDate = [NSString stringWithFormat:@"%@ %@月 %@",szNongli,szNongliDay,(NSString *)[cDayName objectAtIndex:wCurDay]];
    //    NSString *lunarDate = [NSString stringWithFormat:@"%@%@ %@",szNongliDay,[THMangerTool language:@"time.month"],(NSString *)[cDayName objectAtIndex:wCurDay]];
    return 0;
}
/**
 *计算球面距离
 */
+(double)LantitudeLongitudeDist:(double )lon1 lat1:(double)lat1 lon2:(double)lon2 lat2:(double) lat2
{
    double er = 6378137; // 6378700.0f;
    //ave. radius = 6371.315 (someone said more accurate is 6366.707)
    //equatorial radius = 6378.388
    //nautical mile = 1.15078
    double radlat1 = PI*lat1/180.0f;
    double radlat2 = PI*lat2/180.0f;
    //now long.
    double radlong1 = PI*lon1/180.0f;
    double radlong2 = PI*lon2/180.0f;
    if( radlat1 < 0 ) radlat1 = PI/2 + fabs(radlat1);// south
    if( radlat1 > 0 ) radlat1 = PI/2 - fabs(radlat1);// north
    if( radlong1 < 0 ) radlong1 = PI*2 - fabs(radlong1);//west
    if( radlat2 < 0 ) radlat2 = PI/2 + fabs(radlat2);// south
    if( radlat2 > 0 ) radlat2 = PI/2 - fabs(radlat2);// north
    if( radlong2 < 0 ) radlong2 = PI*2 - fabs(radlong2);// west
    //spherical coordinates x=r*cos(ag)sin(at), y=r*sin(ag)*sin(at), z=r*cos(at)
    //zero ag is up so reverse lat
    double x1 = er * cos(radlong1) * sin(radlat1);
    double y1 = er * sin(radlong1) * sin(radlat1);
    double z1 = er * cos(radlat1);
    double x2 = er * cos(radlong2) * sin(radlat2);
    double y2 = er * sin(radlong2) * sin(radlat2);
    double z2 = er * cos(radlat2);
    double d = sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)+(z1-z2)*(z1-z2));
    //side, side, side, law of cosines and arccos
    double theta = acos((er*er+er*er-d*d)/(2*er*er));
    double dist  = theta*er;
    return dist;
}
/**
 *计算直径面距离
 */
+(double)distanceBetweenOrderBy:(double)lat1 lat2:(double)lat2 lng1:(double)lng1 lng2:(double)lng2{
    double dd = M_PI/180;
    double x1=lat1*dd,x2=lat2*dd;
    double y1=lng1*dd,y2=lng2*dd;
    double R = 6371004;
    double distance = (2*R*asin(sqrt(2-2*cos(x1)*cos(x2)*cos(y1-y2) - 2*sin(x1)*sin(x2))/2));
    //返回公里数
    //return  distance*1000;
    //返回距离多少米
    return   distance;
}
/**
 *UUID
 */
+(NSString*)GetUUID{
    CFUUIDRef uuid=CFUUIDCreate(CFAllocatorGetDefault());
    CFStringRef stringRef= CFUUIDCreateString(CFAllocatorGetDefault(), uuid);
    NSString *strUUID=[NSString stringWithString:(__bridge NSString *)stringRef];
    CFRelease(uuid);
    CFRelease(stringRef);
    return [NSString stringWithFormat:@"%@",strUUID];
    
}

#pragma mark MAC
// Return the local MAC addy
// Courtesy of FreeBSD hackers email list
// Accidentally munged during previous update. Fixed thanks to mlamb.
+(NSString *) macaddress
{
    int                    mib[6];
    size_t                len;
    char                *buf;
    unsigned char        *ptr;
    struct if_msghdr    *ifm;
    struct sockaddr_dl    *sdl;
    
    mib[0] = CTL_NET;
    mib[1] = AF_ROUTE;
    mib[2] = 0;
    mib[3] = AF_LINK;
    mib[4] = NET_RT_IFLIST;
    
    if ((mib[5] = if_nametoindex("en0")) == 0) {
        printf("Error: if_nametoindex error/n");
        return @"FengYou";
    }
    
    if (sysctl(mib, 6, NULL, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 1/n");
        return @"FengYou";
    }
    
    if ((buf = malloc(len)) == NULL) {
        printf("Could not allocate memory. error!/n");
        return @"FengYou";
    }
    
    if (sysctl(mib, 6, buf, &len, NULL, 0) < 0) {
        printf("Error: sysctl, take 2");
        return @"FengYou";
    }
    
    ifm = (struct if_msghdr *)buf;
    sdl = (struct sockaddr_dl *)(ifm + 1);
    ptr = (unsigned char *)LLADDR(sdl);
    // NSString *outstring = [NSString stringWithFormat:@"%02x:%02x:%02x:%02x:%02x:%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    NSString *outstring = [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x", *ptr, *(ptr+1), *(ptr+2), *(ptr+3), *(ptr+4), *(ptr+5)];
    free(buf);
    
    return [UtilCheck clearSpace:[outstring uppercaseString] isends:NO];
    
}

//生成随机数
+ (NSString *)getVerificationCode
{
    NSArray *strArr = [[NSArray alloc]initWithObjects:@"0",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",nil] ;
    NSMutableString *getStr = [[NSMutableString alloc]initWithCapacity:5];
    for(int i = 0; i < 6; i++) //得到六位随机字符,可自己设长度
    {
        int index = arc4random() % ([strArr count]);  //得到数组中随机数的下标
        [getStr appendString:[strArr objectAtIndex:index]];
        
    }
    return getStr;
}


//生成随机数
/*
 @param endint 除数
 @param Range 范围
 */
+(NSString *)getarc4random:(NSInteger)endint  Range:(NSInteger)rangeindex{
    int i=(int)(arc4random()%endint+rangeindex);
    return [NSString stringWithFormat:@"%ld",(long)i];
}

//比较时间
+(int)compareDate:(NSString*)date01 withDate:(NSString*)date02 dataFormat:(NSString *)dataFormat
{
    int ci;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:dataFormat];
    NSDate *dt1 = [[NSDate alloc] init];
    NSDate *dt2 = [[NSDate alloc] init];
    dt1 = [df dateFromString:date01];
    dt2 = [df dateFromString:date02];
    NSComparisonResult result = [dt1 compare:dt2];
    switch (result)
    {
            //date02比date01大
        case NSOrderedAscending: ci=1; break;
            //date02比date01小
        case NSOrderedDescending: ci=-1; break;
            //date02=date01
        case NSOrderedSame: ci=0; break;
        default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
    }
    return ci;
}

//全角转半角
+(NSString *)convertedAllTohalf:(NSString *)str
{
    NSMutableString *convertedstr = [str mutableCopy];
    CFStringTransform((CFMutableStringRef)convertedstr, NULL, kCFStringTransformFullwidthHalfwidth, false);
    
    return convertedstr;
}


//有空格
+ (BOOL)isHaveSpace:(NSString *)tmpString
{
    NSString *emailRegex = @"[\\s]+";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:tmpString];
    
}
//有中文
+ (BOOL)isHaveChinese:(NSString *)tmpString
{
    
    NSString *emailRegex = @"[\u2E80-\u9FFF]+";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:tmpString];
}
//有数字
+ (BOOL)isHaveNum:(NSString *)tmpString
{
    
    NSString *emailRegex = @"[\\d]+";
    NSPredicate *emailTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", emailRegex];
    return [emailTest evaluateWithObject:tmpString];
}

//判断字符串首首字符是否为字母
+ (BOOL)isFistletter:(NSString *)tempString
{
    NSString *regex= @"[A-Za-z]+";
    NSPredicate*predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex];
    return [predicate evaluateWithObject:tempString];
}

//车牌号验证
+ (BOOL) validateCarNo:(NSString *)carNo
{
    NSString *carRegex = @"^[\u4e00-\u9fa5]{1}[a-zA-Z]{1}[a-zA-Z_0-9]{4}[a-zA-Z_0-9_\u4e00-\u9fa5]$";
    NSPredicate *carTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",carRegex];
    NSLog(@"carTest is %@",carTest);
    return [carTest evaluateWithObject:carNo];
}

//身份证号
+ (BOOL) validateIdentityCard: (NSString *)value
{
    value = [value stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    
    
    int length =0;
    
    if (!value) {
        
        return NO;
        
    }else {
        
        length =(int) value.length;
        
        
        
        if (length !=15 && length !=18) {
            
            return NO;
            
        }
        
    }
    
    // 省份代码
    
    NSArray *areasArray =@[@"11",@"12", @"13",@"14", @"15",@"21", @"22",@"23", @"31",@"32", @"33",@"34", @"35",@"36", @"37",@"41", @"42",@"43", @"44",@"45", @"46",@"50", @"51",@"52", @"53",@"54", @"61",@"62", @"63",@"64", @"65",@"71", @"81",@"82", @"91"];
    
    
    
    NSString *valueStart2 = [value substringToIndex:2];
    
    BOOL areaFlag =NO;
    
    for (NSString *areaCode in areasArray ) {
        
        if ([areaCode isEqualToString:valueStart2]) {
            
            areaFlag =YES;
            
            break;
            
        }
        
    }
    
    
    
    if (!areaFlag) {
        
        return NO;
        
    }
    
    
    
    
    
    NSRegularExpression *regularExpression;
    
    NSUInteger numberofMatch;
    
    
    
    int year =0;
    
    switch (length) {
            
        case 15:
            
            year = [value substringWithRange:NSMakeRange(6,2)].intValue +1900;
            
            
            
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}$"
                                     
                                                                        options:NSRegularExpressionCaseInsensitive
                                     
                                                                          error:nil];//测试出生日期的合法性
                
            }else {
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}$"
                                     
                                                                        options:NSRegularExpressionCaseInsensitive
                                     
                                                                          error:nil];//测试出生日期的合法性
                
            }
            
            numberofMatch = [regularExpression numberOfMatchesInString:value
                             
                                                               options:NSMatchingReportProgress
                             
                                                                 range:NSMakeRange(0, value.length)];
            
            
            
            if(numberofMatch >0) {
                
                return YES;
                
            }else {
                
                return NO;
                
            }
            
        case 18:
            
            
            year = [value substringWithRange:NSMakeRange(6,4)].intValue;
            
            if (year %4 ==0 || (year %100 ==0 && year %4 ==0)) {
                
                
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}[0-9Xx]$"
                                     
                                                                        options:NSRegularExpressionCaseInsensitive
                                     
                                                                          error:nil];//测试出生日期的合法性
                
            }else {
                
                regularExpression = [[NSRegularExpression alloc]initWithPattern:@"^[1-9][0-9]{5}19[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|1[0-9]|2[0-8]))[0-9]{3}[0-9Xx]$"
                                     
                                                                        options:NSRegularExpressionCaseInsensitive
                                     
                                                                          error:nil];//测试出生日期的合法性
                
            }
            
            numberofMatch = [regularExpression numberOfMatchesInString:value
                             
                                                               options:NSMatchingReportProgress
                             
                                                                 range:NSMakeRange(0, value.length)];
            
            
            
            
            if(numberofMatch >0) {
                
                int S = ([value substringWithRange:NSMakeRange(0,1)].intValue + [value substringWithRange:NSMakeRange(10,1)].intValue) *7 + ([value substringWithRange:NSMakeRange(1,1)].intValue + [value substringWithRange:NSMakeRange(11,1)].intValue) *9 + ([value substringWithRange:NSMakeRange(2,1)].intValue + [value substringWithRange:NSMakeRange(12,1)].intValue) *10 + ([value substringWithRange:NSMakeRange(3,1)].intValue + [value substringWithRange:NSMakeRange(13,1)].intValue) *5 + ([value substringWithRange:NSMakeRange(4,1)].intValue + [value substringWithRange:NSMakeRange(14,1)].intValue) *8 + ([value substringWithRange:NSMakeRange(5,1)].intValue + [value substringWithRange:NSMakeRange(15,1)].intValue) *4 + ([value substringWithRange:NSMakeRange(6,1)].intValue + [value substringWithRange:NSMakeRange(16,1)].intValue) *2 + [value substringWithRange:NSMakeRange(7,1)].intValue *1 + [value substringWithRange:NSMakeRange(8,1)].intValue *6 + [value substringWithRange:NSMakeRange(9,1)].intValue *3;
                
                int Y = S %11;
                
                NSString *M =@"F";
                
                NSString *JYM =@"10X98765432";
                
                M = [JYM substringWithRange:NSMakeRange(Y,1)];// 判断校验位
                
                if ([M isEqualToString:[value substringWithRange:NSMakeRange(17,1)]]) {
                    
                    return YES;// 检测ID的校验位
                    
                }else {
                    
                    return NO;
                    
                }
                
                
            }else {
                
                return NO;
                
            }
            
        default:
            
            return NO;
            
    }
    
    //    BOOL flag;
    //    if (identityCard.length <= 0) {
    //        flag = NO;
    //        return flag;
    //    }
    //    NSString *regex2 = @"^(\\d{14}|\\d{17})(\\d|[xX])$";
    //    NSPredicate *identityCardPredicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",regex2];
    //    return [identityCardPredicate evaluateWithObject:identityCard];
}

//压缩图片
+(UIImage *)imageWithImageSimple:(UIImage *)image scaledToSize:(CGSize)newSize
{
    
    UIImage *newimage;
    if (nil == image) {
        newimage = nil;
    }
    else{
        CGSize oldsize = image.size;
        
        CGRect rect;
        if (newSize.width/newSize.height > oldsize.width/oldsize.height) {
            
            rect.size.width = newSize.width;//newSize.height*oldsize.width/oldsize.height;
            rect.size.height =  newSize.width*oldsize.height/oldsize.width;//newSize.height;
            rect.origin.x = 0;//(newSize.width - rect.size.width)/2;
            rect.origin.y = 0;
            newSize.height=rect.size.height;
        }
        else{
            //平图
            rect.size.width = newSize.width;
            rect.size.height = newSize.width*oldsize.height/oldsize.width;
            rect.origin.x = 0;
            rect.origin.y = 0;//(newSize.height - rect.size.height)/2;
            newSize.height=rect.size.height;
        }
        
        
        UIGraphicsBeginImageContext(newSize);
        CGContextRef context = UIGraphicsGetCurrentContext();
        CGContextSetFillColorWithColor(context, [[UtilCheck hexStringToColor:@"FFFFFF"  alpha:0] CGColor]);
        UIRectFill(CGRectMake(0, 0, newSize.width, newSize.height));//clear background
        [image drawInRect:rect];
        newimage = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
    }
    return newimage;
    
}

//纠正图片
+(UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}

/**
 *绘制虚线 view 所在容器 toyy 距顶部多少距离 颜色
 */
+(CAShapeLayer*)shapeLayer:(UIView*)view  topy:(CGFloat)y StorkeColor:(UIColor*)color{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    //    [shapeLayer setBounds:view.bounds];
    //   [shapeLayer setPosition:view.center];
    [shapeLayer setFillColor:[[UtilCheck hexStringToColor:@"FFFFFF"  alpha:0] CGColor]];
    // 设置虚线颜色为color.CGColor
    [shapeLayer setStrokeColor:color.CGColor];
    // 3.0f设置虚线的宽度
    [shapeLayer setLineWidth:1.0f];
    [shapeLayer setLineJoin:kCALineJoinRound];
    // 3=线的宽度 1=每条线的间距
    
    [shapeLayer setLineDashPattern:
     [NSArray arrayWithObjects:[NSNumber numberWithInt:3],
      [NSNumber numberWithInt:1],nil]];
    
    // Setup the path
    CGMutablePathRef path = CGPathCreateMutable(); //起始点 终止点位置 可以添加多个终点位置划线  0,10代表初始坐标的x，y
    // 320,10代表初始坐标的x，y
    
    CGPathMoveToPoint(path, NULL, 0,0);
    CGPathAddLineToPoint(path, NULL, view.frame.size.width, 0);
    [shapeLayer setPath:path];
    CGPathRelease(path);
    return shapeLayer;
    
}

/**
 *绘制三角形
 */
//@param view 需要加三角形的容器
//@param point 原点
//@param point1 第一点
//@param point2 第二点
//@param StorkeColor  三角形颜色
//@return CAShapeLayer
+(CAShapeLayer*)shapeLayer:(UIView*)view Point:(CGPoint)point Point1:(CGPoint)point1  Point2:(CGPoint)point2 StorkeColor:(UIColor*)color{
    CAShapeLayer *shapeLayer = [CAShapeLayer layer];
    [shapeLayer setFillColor:color.CGColor];
    // 设置虚线颜色为color.CGColor
    [shapeLayer setStrokeColor:color.CGColor];
    // 3.0f设置虚线的宽度
    [shapeLayer setLineWidth:0.0f];
    [shapeLayer setLineJoin:kCALineJoinRound];
    // 3=线的宽度 1=每条线的间距
    // Setup the path
    CGMutablePathRef path = CGPathCreateMutable(); //起始点 终止点位置 可以添加多个终点位置划线  0,10代表初始坐标的x，y
    // 320,10代表初始坐标的x，y
    CGPathMoveToPoint(path, NULL, point.x,point.y);
    CGPathAddLineToPoint(path, NULL, point1.x,point1.y);
    CGPathAddLineToPoint(path, NULL,point2.x,point2.y);
    
    [shapeLayer setPath:path];
    CGPathRelease(path);
    return shapeLayer;
    
}


/**
 *uilabel富文本originStr 文本 headindent首行缩进 默认0 不缩进 lineheight行间距 默认1.0 单倍行距
 */
+(NSMutableAttributedString*)LabelAttributedStrin:(NSString*)originStr HeadIndent:(CGFloat)headindent lineHeightMultiple:(CGFloat)lineheight {
    
    if(lineheight==0){
        lineheight=1.0;
    }
    
    NSMutableAttributedString *attributedStr = [[NSMutableAttributedString alloc] initWithString: originStr];
    NSMutableParagraphStyle *
    style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    style.lineSpacing = 2;//增加行高
    style.lineHeightMultiple = lineheight;//行间距是多少倍
    style.alignment = NSTextAlignmentLeft;//对齐方式
    style.firstLineHeadIndent = headindent;//首行头缩进
    style.paragraphSpacing = 5;//段落后面的间距
    style.paragraphSpacingBefore = 5;//段落之前的间距
    //    style.headIndent = 10;//缩进，相当于左padding
    //    style.tailIndent = -10;//尾部缩进相当于右padding
    
    
    [attributedStr addAttribute:NSParagraphStyleAttributeName value:style range:NSMakeRange(0, originStr.length)];
    
    
    return attributedStr;
}

/**
 *返回范围 文本  最大范围 字号
 */
+(CGSize)sizeWithString:(NSString *)string CGsize:(CGSize)size font:(UIFont *)font
{
    //限制最大的宽度和高度
    CGRect rect = [string boundingRectWithSize:size
                                       options:NSStringDrawingTruncatesLastVisibleLine | NSStringDrawingUsesFontLeading  |NSStringDrawingUsesLineFragmentOrigin//采用换行模式
                                    attributes:@{NSFontAttributeName: font}//传人的字体字典
                                       context:nil];
    
    return rect.size;
}
/**
 *存储图片到本地 沙盒路径 Loationstring image  图片资源
 */
+(NSString*)SaveImageToLoation:(NSString*)Loationstring FromImage:(UIImage*)image FilePath:(NSString*)filename{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    //判断MyImageFolder文件夹是否存在
    BOOL fileExists = [fileManager fileExistsAtPath:Loationstring];
    if(!fileExists)
    {
        [fileManager createDirectoryAtPath:Loationstring withIntermediateDirectories:YES attributes:nil error:nil];
    }
    
    
    NSString *UploadImageFilePath = [Loationstring stringByAppendingPathComponent:filename];  //整张图片路径
    
    //1.
    //把图片数据写入沙盒目录
    NSData *ImageData = UIImageJPEGRepresentation([UtilCheck fixOrientation:image],1.0);  //jpg 压缩读取
    BOOL isY=[ImageData writeToFile:UploadImageFilePath atomically:NO]; //写入文件
    
    if(isY){
        return UploadImageFilePath;
    }
    return nil;
}
/**
 *删除存储到本地的图片 沙盒路径 Loationstring ext 拓展名
 */
+(BOOL)DeleteImageToLoation:(NSString*)Loationstring pathExtension:(NSString*)ext{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    
    NSArray *contents = [fileManager contentsOfDirectoryAtPath:Loationstring error:NULL];
    NSEnumerator *e = [contents objectEnumerator];
    NSString *filename;
    while ((filename = [e nextObject])) {
        
        if (ext!=nil&& [[filename pathExtension] isEqualToString:ext]) {
            
            [fileManager removeItemAtPath:[Loationstring stringByAppendingPathComponent:filename] error:NULL];
        }
        else{
            [fileManager removeItemAtPath:[Loationstring stringByAppendingPathComponent:filename] error:NULL];
        }
    }
    return YES;
    
}

/**
 *字符串忽略大小写比较等值
 */
+(BOOL)compareString:(NSString*)str1 compareString2:(NSString*)str2{
    if([[NSString stringWithFormat:@"%@",str1] compare:[NSString stringWithFormat:@"%@",str2] options:NSCaseInsensitiveSearch]== NSOrderedSame){
        return YES;
    }
    return NO;
}
/**
 *str1字符串是否包含str2
 */
+(BOOL)compareString:(NSString*)str1 ContaincompareString2:(NSString*)str2{
    if([str1 rangeOfString:str2].location !=NSNotFound)
    {
        return YES;
    }
    
    return NO;
}
/**
 *string 全部小写 lower yes
 */
+(NSString*)comparelowercaseString:(NSString*)str1 isLower:(BOOL)lower {
    if(lower){
        return  [str1 lowercaseString];
    }
    else{
        return  [str1 uppercaseString];
    }
    
}

/**
 *图片加文字水印
 */
//@param img 需要加水印的图片
//@param size  加入没图片size未水印区域
//@param text1 水印文字
//@param msakRect 水印位置 CGRectZero 则不处理
//@param  dict 文字属性 nil则默认
//@return 加好水印的图片
+(UIImage *)addText:(UIImage *)img ImageSize:(CGSize)size text:(NSString *)text1 msakRect:(CGRect)rect TextDict:(NSDictionary*)dict
{
    //1.获取上下文
    int w =0;
    int h = 0;
    if(nil==img){
        w=size.width;
        h=size.height;
    }
    else{
        w=img.size.width;
        h=img.size.height;
    }
    //2.绘制图片
    UIGraphicsBeginImageContext(size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGContextTranslateCTM(ctx, 0, img.size.height); //画布的高度
    CGContextScaleCTM(ctx, 1.0, -1.0); //画布翻转
    
    if(nil==img){
        CGContextDrawImage(ctx, CGRectMake(0, 0, w, h),NULL);//将img绘至context上下文中
    }
    else{
        CGContextDrawImage(ctx, CGRectMake(0, 0, w, h), img.CGImage);//将img绘至context上下文中
    }
    
    
    
    NSMutableParagraphStyle *style = [[NSMutableParagraphStyle defaultParagraphStyle] mutableCopy];
    style.alignment = NSTextAlignmentCenter;
    //文字的属性
    if(nil==dict){
        //属性设置参考http://www.th7.cn/Program/IOS/201403/180653.shtml
        NSShadow *shadow=[[NSShadow alloc] init];
        shadow.shadowBlurRadius=5;
        shadow.shadowColor=[UIColor blueColor];
        shadow.shadowOffset=CGSizeMake(1, 3);
        
        dict = @{
                 
                 NSFontAttributeName:[UIFont systemFontOfSize:28],
                 
                 NSParagraphStyleAttributeName:style,
                 
                 NSForegroundColorAttributeName:[UIColor whiteColor],
                 //                 NSBackgroundColorAttributeName:[UIColor colorWithRed:99/255.f green:99/255.f blue:99/255.f alpha:0.45],
                 NSStrokeColorAttributeName:[UIColor colorWithRed:99/255.f green:99/255.f blue:99/255.f alpha:0.45],
                 NSStrokeWidthAttributeName:[NSNumber numberWithInt:3],
                 //                 NSStrikethroughStyleAttributeName:@(NSUnderlineStyleSingle),
                 //                 NSUnderlineStyleAttributeName:@(NSUnderlineStyleSingle),
                 NSObliquenessAttributeName:@1,
                 NSShadowAttributeName:shadow,
                 };
    }
    
    CGContextTranslateCTM(ctx, 0, img.size.height);
    
    CGContextScaleCTM(ctx, 1.0, -1.0);
    //将文字绘制上去
    [text1 drawInRect:rect withAttributes:dict];
    
    //4.获取绘制到得图片
    UIImage *watermarkImage = UIGraphicsGetImageFromCurrentImageContext();
    
    
    
    //5.结束图片的绘制
    UIGraphicsEndImageContext();
    
    
    
    return watermarkImage;
}
/**
 *图片加图片水印
 */
+(UIImage *)addImageLogo:(UIImage *)img text:(UIImage *)logo msakRect:(CGRect)rect{
    int w = img.size.width;
    int h = img.size.height;
    int logoWidth = logo.size.width;
    int logoHeight = logo.size.height;
    //2.绘制图片
    UIGraphicsBeginImageContext(img.size);
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    
    CGContextTranslateCTM(ctx, 0, img.size.height);
    
    CGContextScaleCTM(ctx, 1.0, -1.0);
    
    CGContextDrawImage(ctx, CGRectMake(0, 0, w, h), img.CGImage);
    CGContextDrawImage(ctx, CGRectMake(w-logoWidth, 0, logoWidth, logoHeight), [logo CGImage]);
    //4.获取绘制到得图片
    UIImage *watermarkImage = UIGraphicsGetImageFromCurrentImageContext();
    //5.结束图片的绘制
    UIGraphicsEndImageContext();
    return watermarkImage;
    
}
/**
 *加半透明的水印
 */
+(UIImage *)addImage:(UIImage *)useImage addImage1:(UIImage *)addImage msakRect:(CGRect)rect{
    
    
    
    UIGraphicsBeginImageContext(useImage.size);
    [useImage drawInRect:CGRectMake(0, 0, useImage.size.width, useImage.size.height)];
    [addImage drawInRect:CGRectMake(0, useImage.size.height-addImage.size.height, addImage.size.width, addImage.size.height)  blendMode:kCGBlendModeMultiply alpha:0.74f];
    if (!CGRectEqualToRect(rect, CGRectZero)){
        [addImage drawInRect:rect];
    }
    UIImage *resultingImage = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return resultingImage;
    
}

/**
 *去掉导航黑线
 */
+(UIImage*)ClearBlackNavigation:(UIColor*)color{
    
    CGRect rect = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width,1);
    
    UIGraphicsBeginImageContext(rect.size);
    
    CGContextRef context = UIGraphicsGetCurrentContext();
    
    CGContextSetFillColorWithColor(context,
                                   
                                   color.CGColor);
    
    
    CGContextFillRect(context, rect);
    
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    
    UIGraphicsEndImageContext();
    return img;
}

/**
 *随机生成名字 isUName 是否是用户昵称
 */
+(NSString*)RandomName{
    
    NSString *nameString=nil;
    NSArray *nameArray= @[@"这时候￤",@"一份執著",@"甘愿为你改变",@"习惯了、就好╮",@"你可以相信我〃",@"一無所有 ╯",@"思念绕指尖、",@"′雷克萨斯",@"度娘°",@"淡淡dě忧郁﹎",@"许我一世温柔",@"情、何以堪。",@"好自为之、",@"苦情歌",@"回眸一笑、可倾天下",@"现实太现实。",@"-第二颗纽扣 该送给谁-",@"你所谓的、爱",@"离线留言mmmm",@" 自不量力。",@" 痛~de高貴",@"你的温柔不属于我",@"①笶侕濄",@"红颜ヘ多祸水",@"√透明的 爱",@"阳光下的阴霾",@"寂寞其实是一种无奈",@"n1卜懂d3寂寞",@"待糘荖漢",@"奥特曼打怪兽",@"擦肩而过",@"相濡以沫　ゝ",@"笨蛋丶你这个大美女。",@"经典·1956",@"≮淡忘过去≯",@"锦上添花",@"爱情使你忘记时间",@"曾经心痛ヽ",@"ヤ經典壞疍",@"想入霏霏╮",@"一群势力眼〃",@"拆不穿的谎言、",@"相见不如怀念",@"没 企图",@"太坚强是软弱",@"害羞的斑马",@"被时间扑了空",@"白天的夜猫子",@"该用户已成仙",@"←⒛⒑♀哎哟",@"3秒的、情誼",@"清醇，",@"瀦是の念转倒い",@"Ｔhe Ｅnd、",@"超短裙丶尽显女子应有媚",@"灿若桃花｀ わ",@"我要还你自由",@"微笑 扯痛嘴角 ヽ",@"如何视而不见",@"心牵心 -",@"如既往。",@"左手牵起右手゛",@"ぐ低調 曖昧″",@"不浪漫的罪名↘",@"只有爱情、何来生活╰",@"携手白头的冲动",@"千言万语　≈",@"绘世浮夸 つ",@"相見恨晚",@"欣賞ヽ失戀",@"慢热",@"陪迩到最后╮",@"痴男怨女。",@"你的泪会说慌 ∞",@"ミ 倾一刻温柔",@"普羅旺斯的淚",@"一剪梅",@"花汁、染红指甲",@" ノ指尖的温柔",@"’僅 此 而 已",@"万花︵筒",@"一念之间°",@"容易受伤的梦",@"旧城",@"复制人生",@"最后的最后 ◢",@"自作自受。",@" 、笑叹词穷",@"光辉岁月丶",@"华丽的冒险",@"一张白纸-°",@"笑着唱情歌﹌",@"ａ１、不值钱",@"花心蝴蝶℅",@"失宠而娇",@"你是一只乌鸦",@"跳舞的糖果仙子",@"微笑的天使",@"天然论坛",@"尘风？",@"生若夏花之灿烂",@"天使羽翼",@"●.温馨小筑",@"怡红院",@" 沫沫大队",@"大彼岸",@"月落乌啼霜满天",@"安静角落",@"宁静晨曦",@"月落花满楼!!",@"该玩的年纪却动了心",@"梦毁千百次",@"丢不掉的凄凉",@"往北的地方海未眠。",@"记忆在耳朵里说话",@"笨蛋丶你已经无可取代",@"这边风景独好﹌",@"林荫小道的小女生╰╮",@"分开后一直把你藏在心底",@" *▓亲爱德2.小姐。",@"其实你是我唯一我在乎的",@"你的泪。痛了我的心",@"冻结心里的那一角",@"回眸ゝ淚傾城",@"≌黑夜它依旧沉默",@"|▍痛彻心扉却没有割舍",@"喂.黑涩会的小姐",@"路邊,撿壹份愛○◎",@"男R3n也要有尊严°",@"[ 听 海哭的声音]",@"离歌且莫翻新阕",@"Love song 情歌.",@"末日前最后的问候。",@"三年梦七年痛。",@"第三者的第三者◆",@"只给你一个人℃",@"心失控",@" ♥ 年少的少年。",@"一层一层剥开我的心.",@"半城繁华·半城伤",@"╭　　　不妥的结局°",@"你我敌不过的岁月丶",@"-我是雨天娃娃。",@"你真旳让我ゝ狠狠狠失望▓",@"兵荒马乱的小青春~",@"如果一开始没有太多期许丶",@" 你的爱就像toy",@"一直都这样ヽ",@"悲哀的我，一生等待。。",@"﹏念着阿弥陀佛的上帝。",@"雷雨天丶心碎",@"看う得到的未必能成全",@"ぃ你当我什么",@"有我无我又﹏如何",@"被耍的女人心最狠*",@"-请叫我少楠哥、",@"恰似迩的温柔",@"缌焾丶識①緟靐",@"゛一杯二锅头丶呛得眼泪流",@"不心动°不心痛",@"一个视你如命的女R3n"];
    int i=arc4random()%([nameArray count]-1);
    nameString=[nameArray objectAtIndex:i];
    
    return nameString;
    
}


/**
 *删除本地图片
 */
+(void)DeleLocationimage:(NSString*)url{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    
    BOOL bRet = [fileManager fileExistsAtPath:url];
    if (bRet) {
        //
        NSError *err;
        [fileManager removeItemAtPath:url error:&err];
    }
}

/**
 *api 签名生成
 */
+(NSString*)APPautograph:(NSMutableDictionary*)dict{
    NSString *sign=@"";
    
    if([dict allKeys].count>0){
        NSArray* arr = [dict allKeys];
        
        arr = [arr sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
            NSComparisonResult result = [obj1 compare:obj2];
            return result==NSOrderedDescending;
        }];
        
        for (int i=0; i<arr.count; i++) {
            
            NSString *postkey=arr[i];
            
            //校验是否属于文本
            BOOL isString=[self KeyValueHasString:dict KeyStr:postkey];
            if(isString){
                if(i==0){
                    
                    sign=[sign stringByAppendingString:[NSString stringWithFormat:@"%@=%@",postkey,[self KeyFomat:dict Key:postkey]]];
                }
                else{
                    sign=[sign stringByAppendingString:[NSString stringWithFormat:@"&%@=%@",postkey,[self KeyFomat:dict Key:postkey]]];
                    
                }
                
            }
            else{
                
                NSString *KEYVALUE=@"";//键值对默认值
                
                if([[dict objectForKey:postkey] isKindOfClass:[NSArray class]]){
                    NSArray* arrKey =[dict objectForKey:postkey];
                    
                    NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"pic" ascending:YES]];
                    
                    [arrKey sortedArrayUsingDescriptors:sortDescriptors];
                    
                    //遍历键值
                    for(int j=0;j<arrKey.count;j++){
                        
                        NSDictionary *arrdict=[arrKey objectAtIndex:j];
                        
                        NSArray* arrdictKey = [arrdict allKeys];
                        
                        arrdictKey = [arrdictKey sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
                            NSComparisonResult result = [obj1 compare:obj2];
                            return result==NSOrderedDescending;
                        }];
                        
                        //遍历键值
                        for(int a=0;a<arrdictKey.count;a++){
                            
                            KEYVALUE=[KEYVALUE stringByAppendingString:[NSString stringWithFormat:@"&%@[][%@]=%@",postkey,arrdictKey[a],[self KeyFomat:[arrdict mutableCopy] Key:arrdictKey[a]]]];
                        }
                        
                        
                    }
                    
                }
                else{
                    NSDictionary *keyValue=[dict objectForKey:postkey];//获取键值
                    
                    
                    NSArray* arrKey = [keyValue allKeys];
                    
                    arrKey = [arrKey sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2){
                        NSComparisonResult result = [obj1 compare:obj2];
                        return result==NSOrderedDescending;
                    }];
                    
                    
                    //遍历键值
                    for(int j=0;j<arrKey.count;j++){
                        
                        
                        KEYVALUE=[KEYVALUE stringByAppendingString:[NSString stringWithFormat:@"&%@[%@]=%@",postkey,arrKey[j],[self KeyFomat:[keyValue mutableCopy] Key:arrKey[j]]]];
                        
                        
                    }
                    
                }
                
                
                
                if(i==0){
                    KEYVALUE=[KEYVALUE substringFromIndex:1];
                }
                
                
                sign=[sign stringByAppendingString:KEYVALUE];
            }
            
        }
    }
    
    sign=[UtilCheck stringreplace:[UtilCheck clearSpace:sign isends:NO ] Replace:@"%20" Target:@""];
    //    sign=[sign stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSLog(@"sign:%@",sign);
    if(sign.length>0){
        sign=[RcMD5 ThMD5rule:sign];
    }
    return sign;
}

/**
 服务器加密校验参数是否是字符串
 */
+(BOOL)KeyValueHasString:(NSMutableDictionary*)dict KeyStr:(NSString*)key{
    
    
    if([[dict objectForKey:key] isKindOfClass:[NSString class]]||[[dict objectForKey:key] isKindOfClass:[NSNumber class]]){
        
        return YES;
    }
    else{
        return NO;
    }
}

+(NSString*)KeyFormat:(NSString*)key{
    return key;
}
+(NSString*)KeyFomat:(NSMutableDictionary*)dict Key:(NSString*)key{
    
    
    if([[dict allKeys] containsObject:key]){
        
        return  [UtilCheck stringreplace:[NSString stringWithFormat:@"%@",[dict objectForKey:key]] Replace:@"+" Target:@"_"];
        
    }
    else{
        return @"";
    }
    
    
}



/**
 *百度坐标转为GCJ-02(火星坐标)
 */
+(CLLocationCoordinate2D)TransformationCoordinate2DByBaidu:(CLLocationCoordinate2D)baiduCoordinate{
    CLLocationCoordinate2D GCJCoordinate = [TQLocationConverter transformFromBaiduToGCJ:baiduCoordinate];
    return GCJCoordinate;
    
    
}

/**
 *GCJ-02(火星坐标)转为百度坐标
 */
+(CLLocationCoordinate2D)TransformationCoordinate2DByGaode:(CLLocationCoordinate2D)gaodeCoordinate{
    
    CLLocationCoordinate2D  baiduCoordinate = [TQLocationConverter transformFromGCJToBaidu:gaodeCoordinate];
    
    return baiduCoordinate;
}

/**
 *将GCJ-02(火星坐标)转为WGS-84
 */
+(CLLocationCoordinate2D)TransformationCoordinate2DByGCJ:(CLLocationCoordinate2D)GCJCoordinate{
    
    CLLocationCoordinate2D  WGSCoordinate = [TQLocationConverter transformFromGCJToBaidu:GCJCoordinate];
    
    return WGSCoordinate;
}

/**
 *将WGS-84转为GCJ-02(火星坐标)
 */
+(CLLocationCoordinate2D)TransformationCoordinate2DByWGS:(CLLocationCoordinate2D)WGSCoordinate{
    
    CLLocationCoordinate2D  GCJCoordinate = [TQLocationConverter transformFromWGSToGCJ:WGSCoordinate];
    
    return GCJCoordinate;
}

/**
 *计算时间天以内
 */
+(NSString*)computingTime:(NSInteger)time{
    CGFloat cha=time;
    NSString *timeString=@"";
    if(cha<1){
        //        timeString=[THMangerTool language:@"time.just"];
        return timeString;
    }
    
    else if (cha/3600<1) {
        
        
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        
        timeString = [timeString substringToIndex:timeString.length-7];
        
        //        timeString=[NSString stringWithFormat:@"%@%@", timeString,[THMangerTool language:@"time.minute"]];
        
    }
    
    else if (cha/3600>1&&cha/86400<1) {
        
        timeString = [NSString stringWithFormat:@"%f", cha/3600];
        
        timeString = [timeString substringToIndex:timeString.length-7];
        cha=cha-[timeString intValue]*3600;
        //        timeString=[NSString stringWithFormat:@"%@%@", timeString,[THMangerTool language:@"time.hour"]];
        
        
        NSString *  timefenzhong = [NSString stringWithFormat:@"%f", cha/60];
        
        timefenzhong = [timefenzhong substringToIndex:timefenzhong.length-7];
        
        //        timefenzhong=[NSString stringWithFormat:@"%@%@", timefenzhong,[THMangerTool language:@"time.minute"]];
        
        timeString=[NSString stringWithFormat:@"%@%@",timeString,timefenzhong];
        
    }
    
    else if (cha/86400>1 )
    {
        timeString = [NSString stringWithFormat:@"%f", cha/60];
        
        timeString = [timeString substringToIndex:timeString.length-7];
        
        //        timeString=[NSString stringWithFormat:@"%@%@", timeString,[THMangerTool language:@"time.minute"]];
        
    }
    return timeString;
}
/**
 * 计算距离 厘米换 公里
 */
+(CGFloat)calculatedDistance:(NSInteger)distance{
    CGFloat f=distance;
    return f/1000;
}

/**
 *  判断是不是不在中国
 */
+(BOOL)isLocationOutOfChina:(CLLocationCoordinate2D)location
{
    if (location.longitude < 72.004 || location.longitude > 137.8347 || location.latitude < 0.8293 || location.latitude > 55.8271)
        return YES;
    return NO;
}

/**
 *  自动刷新是否可以
 */
+(BOOL)isAutoRefresh:(NSDate*)lastUpdatedTime{
    NSDate *date = [NSDate date];
    NSTimeInterval secondsInterval= [date timeIntervalSinceDate:lastUpdatedTime];
    if(secondsInterval>120){//时间大于1分钟 自动刷新
        return YES;
    }
    else{
        return NO;
    }
}

/*用户是否勾选记住账户 */
+(BOOL)IsKeepAccount{
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    if([[user objectForKey:KEEP] intValue]==1){
        return YES;
    }
    else{
        return NO;
    }
}
/**
 * 清理记住账户
 */
+(void)setKeepAccount:(BOOL)IsKeep{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    if(IsKeep){
        [user setObject:@"1" forKey:KEEP];
    }
    else{
        
        [user removeObjectForKey:KEEP];
        
    }
    [user synchronize];
}

/**
 *  获取版本号
 */
+(NSString*)getVersion{
    
    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    
    NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
    
    //    NSString *app_build = [infoDictionary objectForKey:@"CFBundleVersion"];
    
    
    return [NSString stringWithFormat:@"%@",app_Version];
}

/**
 *  获取APP名称
 */
+(NSString*)getAppName{
    //    NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
    
    NSString *app_Name =  NSPublicLocalizedString(@"CFBundleDisplayNames", @"");
    
    return app_Name;
}
/**
 *  获取APP类别 Happyi | THRC
 */
+(NSString*)getAppType{
    
    NSString *app_Type =  NSPublicLocalizedString(@"APPType", @"");
    
    return app_Type;
}

/**
 * 是否首次进入APP
 */
+(BOOL)isStatrOpenApp{
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    if([[user objectForKey:[NSString stringWithFormat:@"%@",START]] intValue]==1){
        return NO;
        
    }
    else{
        return YES;
    }
    
}

/**
 *保存用户已经进入首页
 */
+(void)savetStatrOpenApp{
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    [user setObject:@"1" forKey:[NSString stringWithFormat:@"%@",START]];
    [user synchronize];
    
}

/**
 *用户是否进行过新手指引
 */
+(BOOL)isPerfect{
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    if([[user objectForKey:[NSString stringWithFormat:@"%@",START]] intValue]==1){
        return NO;
    }
    else{
        
        return YES;
    }
}

/**
 *保存用户是否进行过新手指引
 */
+(void)savePerfect{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    [user setObject:@"1" forKey:[NSString stringWithFormat:@"%@",START]];
    [user synchronize];
}


/**
 *保存分享数据
 */
+(void)saveShareData:(NSDictionary*)shareDice{
    
    [[NSUserDefaults standardUserDefaults] setObject:shareDice forKey:SHARE];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}
/**
 *获取保存分享数据
 */
+(NSDictionary*)getShareData{
    
    NSMutableDictionary *dict=[[NSMutableDictionary alloc] initWithCapacity:0];
    dict=[NSMutableDictionary dictionaryWithDictionary:[[[NSUserDefaults  standardUserDefaults] objectForKey:SHARE] copy]];
    
    if (![[dict allKeys] containsObject:@"title"]) {
        [dict setObject:[NSString stringWithFormat:@"来自%@的分享",[self getAppName]] forKey:@"title"];
    }
    
    if (![[dict allKeys] containsObject:@"image"]) {
        [dict setObject:[NSString stringWithFormat:@"http://static.happiyi.com/icon117.png"] forKey:@"image"];
    }
    
    if ([[dict allKeys] containsObject:@"content"]) {
        
        NSString *content=[dict objectForKey:@"content"];
        if(content.length>80){
            
            content=[content substringWithRange:NSMakeRange(0, 80)];
            [dict setObject:content forKey:@"content"];
        }
        
        
    }
    
    if ([[dict allKeys] containsObject:@"description"]) {
        
        NSString *content=[dict objectForKey:@"description"];
        if(content.length>80){
            
            content=[content substringWithRange:NSMakeRange(0, 80)];
            [dict setObject:content forKey:@"description"];
        }
    }
    
    return dict;
}


/**
 *获取用户修改头像时间
 */
+(NSString*)setUpHeadDateTime:(BOOL)isOnliytime{
    
    
    //更新缓存
    if([[[NSUserDefaults standardUserDefaults] objectForKey:HEADIMAGETIME] allKeys].count>0){
        
        NSMutableDictionary *temp=[NSMutableDictionary dictionaryWithDictionary:[[NSUserDefaults standardUserDefaults] objectForKey:HEADIMAGETIME]];
        if(isOnliytime){
            NSString *dataTime=[UtilCheck stringByDate:[NSDate date] dateFormatter:@"yyyy-MM-dd HH:mm:ss"];
            
            [[NSUserDefaults standardUserDefaults] setObject:[NSDictionary dictionaryWithObjectsAndKeys:dataTime,@"apptime", nil] forKey:HEADIMAGETIME];
            [[NSUserDefaults standardUserDefaults] synchronize];
            NSLog(@"dataTime:%@",dataTime);
            return dataTime;
        }
        else{
            //六个小时更新一次数据  1分钟更新一次
            if([UtilCheck TimeCache:[NSString stringWithFormat:@"%@",[temp objectForKey:@"apptime"]]]>=3*IMAGE_TIME)
            {
                NSString *dataTime=[UtilCheck stringByDate:[NSDate date] dateFormatter:@"yyyy-MM-dd HH:mm:ss"];
                
                [[NSUserDefaults standardUserDefaults] setObject:[NSDictionary dictionaryWithObjectsAndKeys:dataTime,@"apptime", nil] forKey:HEADIMAGETIME];
                [[NSUserDefaults standardUserDefaults] synchronize];
                NSLog(@"dataTime:%@",dataTime);
                
                return dataTime;
            }
            else{
                if([[temp allKeys] containsObject:@"apptime"]){
                    NSLog(@"dataTime:%@",[temp objectForKey:@"apptime"]);
                    return  [NSString stringWithFormat:@"%@",[temp objectForKey:@"apptime"]];
                    
                }
                else{
                    
                    NSString *dataTime=[UtilCheck stringByDate:[NSDate date] dateFormatter:@"yyyy-MM-dd HH:mm:ss"];
                    
                    [[NSUserDefaults standardUserDefaults] setObject:[NSDictionary dictionaryWithObjectsAndKeys:dataTime,@"apptime", nil] forKey:HEADIMAGETIME];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                    NSLog(@"dataTime:%@",dataTime);
                    return dataTime;
                    
                }
            }
            
        }
        
    }else{
        
        
        NSString *dataTime=[UtilCheck stringByDate:[NSDate date] dateFormatter:@"yyyy-MM-dd HH:mm:ss"];
        
        [[NSUserDefaults standardUserDefaults] setObject:[NSDictionary dictionaryWithObjectsAndKeys:dataTime,@"apptime", nil] forKey:HEADIMAGETIME];
        [[NSUserDefaults standardUserDefaults] synchronize];
        NSLog(@"dataTime:%@",dataTime);
        return dataTime;
    }
    
}

/**
 *是否出在审核阶段 默认在审核
 */
+(BOOL)isAPPStoreExamine{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    //在审核
    if([[user objectForKey:[NSString stringWithFormat:@"%@",APPExamine]] intValue]!=2 ){
        return YES;
    }
    else{
        return NO;
    }
}

/**
 *修改审核阶段 IsAPPStore YES  在审核
 */
+(void)setAPPStoreExamine:(BOOL)IsAPPStore{
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    
    if(IsAPPStore){
        //在审核
        [user setObject:@"1" forKey:[NSString stringWithFormat:@"%@",APPExamine]];
    }
    else{
        //没有在审核
        [user setObject:@"2" forKey:[NSString stringWithFormat:@"%@",APPExamine]];
    }
    [user synchronize];
}
/**
 *  将数组转化成数据模型
 *
 *  @param array 待转化数组
 *  @param model 目标模型
 *
 *  @return 转化结果
 */
+(NSMutableArray*)arraytoModel:(NSArray*)array targetModel:(NSString*)model{
    NSMutableArray *resultArray=[[NSMutableArray alloc] initWithCapacity:0];
    if(!array){
        return nil;
    }
    for(int i=0;i<array.count;i++){
        id myObj =  [(BaseModel*)[NSClassFromString(model) alloc] initContentWithDic:array[i]];
        [resultArray addObject:myObj];
    }
    
    return resultArray;
    
}

/**
 *  数据字典转化成数据模型
 *
 *  @param dic   待转化字典
 *  @param model 目标模型
 *
 *  @return 转化结果
 */
+(id)dictionarytoModel:(NSDictionary*)dic targetModel:(NSString*)model{
    if(!dic){
        return nil;
    }
    id myObj =  [(BaseModel*)[NSClassFromString(model) alloc] initContentWithDic:dic];
    return myObj;
}

/**
 将十进制的坐标字符串转化为度分秒的形式
 ** 转化进制为 60
 ** 整数部分为 ° ； 小数部分 * 60 后的整数部分为分， 小数部分 * 60 后的小数部分再 * 60 为秒。
 @param coordinateString 十进制坐标的字符串
 @param key 经纬度的key 纬度为 latitude  经度为 longitude
 @return 度分秒的字符串
 */
+ (NSString *)coordinateFormConverter:(NSString *)coordinateString  coordinateKey:(NSString *)key{
    
    CGFloat coordinate = [coordinateString floatValue];
    
    NSString *direction = nil;
    
    // 经度
    if ([key isEqualToString:@"longitude"]) {
        if (coordinate > 0) {
            direction = @" E";
        }
        else {
            direction = @" W";
        }
    }
    // 纬度
    if ([key isEqualToString:@"latitude"]) {
        if (coordinate > 0) {
            direction = @" N";
        }
        else {
            direction = @" S";
        }
    }
    // 转换为正数
    coordinate = fabs(coordinate);
    
    // 度 整数部分即为°
    NSInteger degree = labs([coordinateString integerValue]);
    // 分
    CGFloat minutesCoordinate = (coordinate - degree) * 60.f;
    NSInteger minutes = (int)minutesCoordinate;
    // 秒
    CGFloat secondsCoordinate = (minutesCoordinate - minutes) * 60.f;
    // 转化为字符串
    NSString *resultStr = [NSString stringWithFormat:@"%ld°%ld'%.1f\"%@",(long)degree,(long)minutes,secondsCoordinate,direction];
    return resultStr;
}

#pragma mark- 关于语言
+(LanguageType)getLanageType {
    
    NSNumber *number =[[NSUserDefaults standardUserDefaults] objectForKey:@"LANGUAGE"];
    if(number){
        return [number integerValue];
    }
    return  NSLanguageDefault;
}

+ (LanguageType)getPreferredLanguage {
    NSArray *languages = [NSLocale preferredLanguages];
    NSString * preferredLang = [languages objectAtIndex:0];
    NSLog(@"preferredLang is --%@",preferredLang);
    
    if ([preferredLang hasPrefix:@"zh"]) {
        return NSLanguageChineese;
    }
    else if ([preferredLang hasPrefix:@"en"]) {
        return NSLanguageEnglish;
    }
    else{
        return NSLanguageEnglish;
    }
}

/**
 *  修改语言
 */
+(void)setLanguage:(LanguageType)languageType{
    
    NSUserDefaults *user=[NSUserDefaults standardUserDefaults];
    
    [user setObject:[NSNumber numberWithInteger:languageType] forKey:@"LANGUAGE"];
    
    [user synchronize];
}

/**
 *  获取语言话文字
 *  @return 返回文字
 */
+ (NSString*)language:(NSString*)key{
    NSInteger tag=0;
    
    NSNumber *number=[[NSUserDefaults standardUserDefaults] objectForKey:@"LANGUAGE"];
    if(number){
        tag=[number integerValue];
    }
    if(tag == NSLanguageChineese){
        return NSLocalizedStringFromTable(key,@"Chinese",nil);
    }
    else if (tag==NSLanguageEnglish){
        return NSLocalizedStringFromTable(key,@"English",nil);
    }
   
    else{
        return NSLocalizedStringFromTable(key,@"Chinese",nil);
    }

}

@end

